import React, { useState, useRef, useEffect } from 'react';
import classnames from 'classnames';
import { Progress, message } from 'antd';
import videoBg from '../images/video.png';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import styles from './index.less';
import { isImg, isVideo, uid } from '@/utils';
import type { InnterUploadProps } from '../InnerUpload';
import InnerUpload from '../InnerUpload';
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

const SortableItem = SortableElement(({ item, items, itemIndex, onRemove, onPreview, column }) => {
  const isimg = isImg(item.name);
  const isvideo = isVideo(item.name);
  const percent = item.percent ? parseInt(item.percent) : 0;

  return (
    <div key={item.uid} className={styles.item} style={{ width: `${(100 / column).toFixed(2)}%` }}>
      <div className={styles.content}>
        {isvideo && <div className={styles.header}>{item.name}</div>}
        {isvideo && <div className={styles.img} style={{ backgroundImage: `url(${videoBg})` }} />}
        {isimg && <div className={styles.img} style={{ backgroundImage: `url(${item.url})` }} />}
        {item.status === 'error' && <div className={styles.error}>上传失败</div>}
        {item.status === 'uploading' && (
          <div className={styles.progress}>
            <Progress type="circle" percent={percent > 99 ? 99 : percent} width={60} />
          </div>
        )}
        {(item.status === 'done' || item.status === 'error') && (
          <div className={styles.over}>
            <i className={styles.mask} />
            <div className={styles.main}>
              {item.status === 'done' && (
                <div className={styles.button} onClick={() => onPreview(item)}>
                  <img loading="lazy" className={styles.icon} src={require('../images/play.png')} />
                  查看
                </div>
              )}
              <div className={styles.button} onClick={() => onRemove(itemIndex)}>
                <img loading="lazy" className={styles.icon} src={require('../images/delete.png')} />
                删除
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}) as any;

const SortableList = SortableContainer((props) => {
  const { items, uploadProps, UploadRef, ...restProps } = props;
  const disabled = items.some((item) => item.status === 'uploading');
  return (
    <div className={styles.list}>
      {items.map((item, index) => (
        <SortableItem
          disabled={disabled}
          key={`${item.uid}`}
          index={index}
          itemIndex={index}
          item={item}
          items={items}
          {...restProps}
        />
      ))}
      <div className={styles.item} style={{ width: `${(100 / restProps?.column).toFixed(2)}%` }}>
        <div className={styles.content}>
          <InnerUpload ref={UploadRef} className={styles.drag} {...uploadProps} multiple>
            <div className={styles.addwrapper}>
              <i className={styles.icon} />
              <div className={styles.title}>{restProps.tipsTitle}</div>
              <div className={styles.des}>图片支持 jpg/png/gif 格式</div>
              <div className={styles.des}>视频支持 avi/mp4/mov 格式</div>
              {/* <div className={styles.des}>大小：小于5M</div> */}
              <div className={styles.des}>可拖拽上传</div>
            </div>
          </InnerUpload>
        </div>
      </div>
    </div>
  );
}) as any;

interface FileItem {
  key: any;
  id: any;
  percent?: number;
  status: 'error' | 'uploading' | 'done';
}
type DraggerUploadProps = {
  max?: number;
  size?: number;
  onChange?: (fileList: any[]) => void;
  value?: any[];
  payload?: {};
  action?: string;
  name?: string;
  /**
   * 几列
   */
  column?: number;
  tipsTitle?: string;
  getAliyunAuth?: () => Promise<any>;
  refreshAliyunAuth?: () => Promise<any>;
  onSuccess?: (fileList, file) => void;
  onPreview?: (file) => void;
  onRemove?: (file, index) => void;
  onSortEnd?: (filelist) => void;
} & Partial<Pick<InnterUploadProps, 'getAliyunAuth' | 'refreshAliyunAuth' | 'videoUploadto'>>;

const DraggerUpload: React.FC<DraggerUploadProps> = ({
  size = 50,
  max = 30,
  onChange,
  value = [],
  payload = {},
  action,
  name = 'file',
  onSuccess,
  onPreview,
  onRemove,
  getAliyunAuth,
  refreshAliyunAuth,
  videoUploadto = 'AliyunVideo',
  column = 3,
  tipsTitle = '上传图片/视频',
  onSortEnd: propsOnSortEnd,
}) => {
  const [fileList, setFlieList] = useState<any[]>([...value]);

  const beforeUpload = async (file, _fileList) => {
    message.destroy();
    const isimg = isImg(file.name);
    const isvideo = isVideo(file.name);
    // 格式不符合
    if (!isimg && !isvideo) {
      message.error('图片仅支持 jpg/png/gif 格式, 视频仅支持 avi/mp4/mov 格式');
      return false;
    }

    // 尺寸不符合
    const isSizeOK = file.size < 1024 * 1024 * size;
    if (!isSizeOK && isimg) {
      message.error(`文件大小不能超过 ${size} Mb`);
      return false;
    }

    // 数量超出
    if (_fileList.length >= max) {
      message.error(`最多上传 ${max} 个文件`);
      return false;
    }
    file.key = file?.uid || uid();

    if (isimg) {
      file.url = await getBase64(file);
      // file.url =  URL.createObjectURL(file)
    }
    // else {
    //     file.url = OSSData.host + '/' + OSSData.dir + filename;
    // }

    return file;
  };

  const getExtraData = (file) => {
    return payload;
    // return {
    //     key: file.key,
    //     OSSAccessKeyId: OSSData.accessId,
    //     policy: OSSData.policy,
    //     Signature: OSSData.signature,
    // };
  };

  const handleUploadChange = async (fileList) => {
    setFlieList(fileList);
    onChange?.(fileList);
  };

  const onSortEnd = ({ oldIndex, newIndex }) => {
    const newFileList = [...fileList];
    const targeItem = newFileList[newIndex];
    newFileList[newIndex] = newFileList[oldIndex];
    newFileList[oldIndex] = targeItem;
    setFlieList(newFileList);
    propsOnSortEnd?.(newFileList);
  };
  const UploadRef = useRef<any>();
  const handleRemove = async (index) => {
    const result = (await onRemove?.(fileList[index], index)) ?? true;
    if (result !== true) return;
    UploadRef.current?.removeFile?.(fileList[index]);
    const newFileList = [...fileList];
    newFileList.splice(index, 1);
    setFlieList(newFileList);
  };

  const handleSuccess = async (fileList, file) => {
    onSuccess?.(fileList, file);
  };
  const upLoadProps = {
    fileList,
    onChange: handleUploadChange,
    name,
    action,
    data: getExtraData,
    beforeUpload: beforeUpload,
    onSuccess: handleSuccess,
    videoUploadto,
    getAliyunAuth,
    refreshAliyunAuth,
  };
  const handlePreview = (item) => {
    onPreview?.(item);
  };

  return (
    <div className={classnames(styles.draggerUpload, 'c-dragger-upload-container')}>
      <div className={classnames(styles.tips, 'c-dragger-upload-tips')}>
        推荐尺寸：1800（宽）X2400（高）单文件最大尺寸：2560（宽）X9999（高）
      </div>
      <div className={styles.body}>
        <SortableList
          distance={10}
          axis="xy"
          UploadRef={UploadRef}
          column={column}
          items={fileList}
          onSortEnd={onSortEnd}
          onRemove={handleRemove}
          onPreview={handlePreview}
          uploadProps={upLoadProps}
          tipsTitle={tipsTitle}
        />
      </div>
    </div>
  );
};

export default DraggerUpload;
